import React, {useState, useEffect, lazy} from 'react'
import { Drawer, Tabs, Tooltip, Space } from 'antd'
import { CopyOutlined, FullscreenOutlined } from '@ant-design/icons'
import { ToolsItemType } from '@/components/ToolsGroup'
import { useAppDispatch, useAppSelector } from '@/hooks/app.hooks'
import { addTab, delTab } from "@/slice/opDrawerSlice"
import type {TabItem} from "@/slice/opDrawerSlice"
import { klona } from 'klona'
import LazySuspense from '@/components/LazySuspense'

const JsonEdit = lazy(() => import('@/components/JsonEdit'))
const TimeConv = lazy(() => import('@/components/TimeConv'))
const JwtDecode = lazy(() => import('@/components/JwtDecode'))
const UrlDecode = lazy(() => import('@/components/UrlDecode'))
const Regexper = lazy(() => import('@/components/Regexper'))
const SqlFormatter = lazy(() => import('@/components/SqlFormatter'))

import styles from './index.module.css'


interface OpDrawerProp {
  op: {open: boolean, data?:ToolsItemType},
  onClose?: (e:React.MouseEvent | React.KeyboardEvent) => void
}
type TargetKey = React.MouseEvent | React.KeyboardEvent | string




const OpDrawer:React.FC<OpDrawerProp> = (props) => {
  const { op: {open, data}, onClose } = props

  const tabItems = useAppSelector(state => state.opDrawer.tabItems)
  const dispatch = useAppDispatch()
  const [activeKey, setActiveKey] = useState('')
  const [opDrawerFullscreen, setOpDrawerFullscreen] = useState(false)


  useEffect(() => {
    if (!data) {
      return
    }
    dispatch(addTab(data))
    setActiveKey(data.code)
  }, [data, dispatch])

  // useEffect(() => {
  //   console.log('tabItems变化了:', tabItems)
  // }, [tabItems])

  const getTabs:(items:ToolsItemType[]) => TabItem[] = (items) => {
    return items.map(item => {
      let children

      if (item.code.startsWith('json-edit')) {
        children = <LazySuspense><JsonEdit style={{height: "95%"}}/></LazySuspense>
      } else if (item.code.startsWith('time-conv')) {
        children = <LazySuspense><TimeConv /></LazySuspense>
      } else if (item.code.startsWith('jwt-decode')) {
        children = <LazySuspense><JwtDecode /></LazySuspense>
      } else if (item.code.startsWith('url-decode')) {
        children = <LazySuspense><UrlDecode /></LazySuspense>
      } else if (item.code.startsWith('regexper-ui')) {
        children = <LazySuspense><Regexper /></LazySuspense>
      } else if (item.code.startsWith('sql-formatter')) {
        children = <LazySuspense><SqlFormatter /></LazySuspense>
      }
      
      return {
        key: item.code,
        children: children,
        label: <>
        <span className={styles.tabTitleSpan}>{item.text}</span>
        <Tooltip placement="top" title="复制标签页"  getPopupContainer={() => {
          const doc = document.getElementsByClassName("ant-drawer-content-wrapper")[0]
          return doc as HTMLElement
          }}>
          <CopyOutlined onClick={() => {copyTab(item.code)}} />
        </Tooltip>
        </>
      }
    })
  }

  const copyTab = (code:string) => {
    const source = tabItems.find(item => item.code === code)
    if (source) {
      const newData = klona<ToolsItemType>(source)
      newData.code = `${source.code}_copy`
      dispatch(addTab(newData))
    }
  }

  const onTabsEdit = (targetKey: TargetKey, action: 'add' | 'remove') => {
    if (action === 'remove' && typeof targetKey === "string") {
      dispatch(delTab(targetKey))
      const activeKey = targetKey.substring(0, targetKey.indexOf('_'))
      setActiveKey(activeKey)
      console.log(`删除了:${targetKey},激活了:${activeKey}`)
    }
 
  }


  return (
    <div>
    <Drawer
        title={
          <>
            <Space style={{color: "#1677ff"}}>
              <span style={{color: "rgba(0, 0, 0, 0.88)"}} className={styles.tabTitleSpan}>工作台</span> 
              <Tooltip
                  getPopupContainer={() => {
                    const doc = document.getElementsByClassName("ant-drawer-content-wrapper")[0]
                    return doc as HTMLElement
                  }} 
                  placement="top" 
                  title={opDrawerFullscreen ? "退出全屏" : "全屏"}>
                <FullscreenOutlined onClick={() => {
                  const doc = document.getElementsByClassName("ant-drawer-content-wrapper")
                  if (!opDrawerFullscreen) {
                    doc[0]?.requestFullscreen()
                  } else {
                    document.exitFullscreen()
                  }
                  setOpDrawerFullscreen(!opDrawerFullscreen)
                }}/>
              </Tooltip>
            </Space>

          </>
        }
        placement="right"
        closable={true}
        onClose={(e) => {
          if (onClose) {
            onClose(e)
          }
        }}
        open={open}
        height="90%"
        width="90%"
      >
        {
          // data?.code === 'json-edit' && <JsonEdit style={{height: "90%"}}/>
        }
        <div className='op-drawer-tabs'>
        <Tabs
          hideAdd
          style={{height: "100%"}}
          size="middle"
          onChange={(key) => setActiveKey(key)}
          activeKey={activeKey}
          type="editable-card"
          onEdit={onTabsEdit}
          items={getTabs(tabItems)}
        />
        </div>
        
      </Drawer>
    </div>
  )
}
export default OpDrawer

